<template>
    <div class="max-w-6xl mx-auto">
        <!-- 页面标题 -->
        <div class="mb-6">
            <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-neutral-700">知识文档</h2>
            <p class="text-neutral-500 mt-1">管理和浏览所有文档资源</p>
        </div>

        <!-- 搜索和筛选 -->
        <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
            <div class="flex flex-col sm:flex-row gap-4">
                <div class="relative flex-1">
                    <input type="text" placeholder="搜索文档..." v-model="keyWord"
                        class="w-full pl-10 pr-4 py-2 border border-neutral-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-custom">
                    <i class="fa-solid fa-search absolute left-3 top-1/2 -translate-y-1/2 text-neutral-400"></i>
                </div>
                <div class="flex gap-2">
                    <button
                        class="px-4 py-2 border border-neutral-200 rounded-lg text-neutral-600 hover:bg-neutral-50 transition-custom"
                        @click="filterDocuments">
                        <i class="fa-solid fa-filter mr-1"></i> 筛选
                    </button>
                    <button @click="openUpload"
                        class="px-4 py-2 bg-sky-500 text-white rounded-lg hover:bg-sky-600 transition-custom">
                        <i class="fa-solid fa-plus mr-1"></i> 上传文档
                    </button>
                </div>
            </div>
        </div>

        <!-- 文档列表 -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <!-- 文档卡片 -->
            <div class="bg-white rounded-lg shadow-sm hover:shadow-md transition-custom overflow-hidden"
                v-for="(doc, index) in documents" :key="index">
                <div class="p-4">
                    <div class="flex justify-between items-start mb-3">
                        <h3 class="font-medium text-neutral-700">{{ doc.title }}</h3>
                        <span class="text-xs text-neutral-500 bg-neutral-100 px-2 py-1 rounded">{{ doc.type
                            }}</span>
                    </div>
                    <p class="text-sm text-neutral-500 line-clamp-2">{{ doc.title }}</p>
                    <div class="flex items-center justify-between mt-4 text-xs text-neutral-500">
                        <span>更新于 {{ doc.updateTime }}</span>
                        <el-button @click="deleteDocument(doc.id)" type="danger" :icon="Delete" circle />
                    </div>
                </div>
            </div>
        </div>

        <!-- 模态框用于上传文件 -->
        <div v-if="upload" class="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center">
            <div class="bg-white p-4 rounded-lg relative">
                <el-upload v-model:file-list="fileList" class="upload-demo" :action=uploadURL multiple
                    :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" :limit="0"
                    :on-exceed="handleExceed">
                    <el-button type="primary">点击上传</el-button>
                    <template #tip>
                        <div class="el-upload__tip">
                            只能上传word、pdf、md格式文件，且最大为30MB；
                        </div>
                    </template>
                </el-upload>
                <button @click="closeUpload" class="absolute top-2 right-2">
                    <svg t="1744171280645" class="icon" viewBox="0 0 1066 1024" version="1.1"
                        xmlns="http://www.w3.org/2000/svg" p-id="1242" width="16" height="16">
                        <path
                            d="M789.674667 842.922667L181.248 234.496A37.973333 37.973333 0 0 1 234.922667 180.906667l608.512 608.426666a37.973333 37.973333 0 1 1-53.717334 53.76l-0.042666-0.128z"
                            p-id="1243" fill="#bfbfbf"></path>
                        <path
                            d="M789.76 180.906667a37.973333 37.973333 0 0 1 53.674667 53.674666L235.008 843.093333a37.973333 37.973333 0 1 1-53.674667-53.717333l608.426667-608.426667z"
                            p-id="1244" fill="#bfbfbf"></path>
                    </svg>
                </button>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { UploadProps, UploadUserFile } from 'element-plus';
import { Delete } from '@element-plus/icons-vue';
import { useDocumentApi } from '../../../api/document';
const documentApi = new useDocumentApi();
const uploadURL = import.meta.env.VITE_API_BASE_URL + "/document/upload";
const documents = ref<DocumentItem[]>([]);
const upload = ref(false);

// 文档信息对象接口
interface DocumentItem {
    id: string;
    title: string;
    type: string;
    updateTime: string;
}

const keyWord = ref("");

const openUpload = () => {
    upload.value = true;
}

const closeUpload = () => {
    getDocumentInfos();
    upload.value = false;
}

const fileList = ref<UploadUserFile[]>([])

const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
    console.log(file, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
    console.log(uploadFile)
}

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
    ElMessage.warning(
        `The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
        } totally`
    )
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, _uploadFiles) => {
    return ElMessageBox.confirm(
        `Cancel the transfer of ${uploadFile.name} ?`
    ).then(
        () => true,
        () => false
    )
}

// 根据id删除文档
const deleteDocument = (id: string) => {
    documentApi.deleteDocument(id).then(response => {
        if (response.data.code == 1) {
            ElMessage.success("删除成功！");
            getDocumentInfos();
        } else {
            ElMessage.error(response.data.message);
        }
    }).catch(error => {
        console.error(error);
    });
}

//格式化返回数据
const formatArray = (dataList: any) => {
    documents.value = [];
    let type = "";
    // 格式处理
    for (const index in dataList) {
        if (dataList[index].type == 1) {
            type = "docx";
        } else if (dataList[index].type == 2) {
            type = "pdf";
        } else {
            type = "md";
        }
        documents.value.push({
            id: dataList[index].id,
            title: dataList[index].title,
            type: type,
            updateTime: dataList[index].updateTime,
        })
    }
}

// 获取所有文档信息
const getDocumentInfos = () => {
    documentApi.getDocumentsInfo().then(response => {
        if (response.data.code == 1) {
            let array = response.data.data.dataList;
            formatArray(array);
        } else {
            ElMessage.error(response.data.message);
        }
    }).catch(error => {
        console.error(error);
    })
}

// 关键词筛选
const filterDocuments = () => {
    documentApi.filterDocument(keyWord.value).then(response => {
        if (response.data.code == 1) {
            let array = response.data.data.dataList;
            formatArray(array);
        } else {
            ElMessage.error(response.data.message);
        }
    }).catch(error => {
        console.error(error);
    })
}

onMounted(() => {
    getDocumentInfos();
});
</script>

<style scoped>
/* 全局样式 */
:root {
    --primary-color: #165DFF;
    --neutral-100: #F5F7FA;
    --neutral-200: #E5E6EB;
    --neutral-300: #C9CDD4;
    --neutral-400: #86909C;
    --neutral-500: #4E5969;
    --neutral-600: #272E3B;
    --neutral-700: #1D2129;
}
</style>